package com.haitaoit.chengquan.module.center.activity.info;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.center.adapter.MyForumAdapter;
import com.haitaoit.chengquan.module.center.model.PostModel;
import com.haitaoit.chengquan.module.home.activity.forum.ForumDetailActivity;
import com.haitaoit.chengquan.ui.invitation.activity.EditInvitationActivity;
import com.haitaoit.chengquan.ui.invitation.popu.ReasonPopu;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 论坛
 */
public class MyForumActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pull_to_refresh_scrollview)
    PullToRefreshScrollView pullrefreshscrollview;

    private ScrollView   mScrollView;
    private LinearLayout null_information_layout, search_LL;
    private MyListView listView;
    private EditText   search_et;


    private boolean isFrist = true;
    private int     page    = 1;
    private MyForumAdapter adapter;
    private String forum_type = "1";
    //    private List<PostModel> postModelList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_forum);
        ViewUtils.inject(this);


        View view = LayoutInflater.from(this).inflate(R.layout.scrollview_listview_layout2, null);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        search_LL = (LinearLayout) findViewById(R.id.search_LL);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);
        search_et = (EditText) findViewById(R.id.search_et);
        findViewById(R.id.search_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (search_et.getText().toString().equals("")) {
                    ToastUtils.showToast("请输入搜索内容！");
                } else {
                    forum_type = "1";
                    adapter.setType(forum_type);
                    isFrist = true;
                    page = 1;
                    httpGetuser_esther_list();
                }
            }
        });

        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(true);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        search_LL.setVisibility(View.VISIBLE);
        adapter = new MyForumAdapter(this);
        adapter.setBackCall(backCall);
        adapter.setType(forum_type);
        listView.setAdapter(adapter);
        httpGetuser_esther_list();
    }

    @OnClick({R.id.left, R.id.forum_rb1, R.id.forum_rb2, R.id.forum_rb3,})
    public void onClick(View v) { // 收起键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(search_et.getWindowToken(), 0);
        switch (v.getId()) {
            case R.id.left:
                finish();
                break;
            case R.id.forum_rb1:
                search_LL.setVisibility(View.VISIBLE);
                forum_type = "1";
                adapter.setType(forum_type);
                if (adapter.getCount() > 0)
                    adapter.getList().clear();
                adapter.notifyDataSetChanged();
                isFrist = true;
                page = 1;
                httpGetuser_esther_list();
                break;
            case R.id.forum_rb2:
                search_LL.setVisibility(View.GONE);
                search_et.setText("");
                forum_type = "2";
                adapter.setType(forum_type);
                if (adapter.getCount() > 0)
                    adapter.getList().clear();
                adapter.notifyDataSetChanged();
                isFrist = true;
                page = 1;
                httpGetuser_esther_comments_list();
                break;
            case R.id.forum_rb3:
                search_LL.setVisibility(View.GONE);
                search_et.setText("");
                forum_type = "3";
                adapter.setType(forum_type);
                if (adapter.getCount() > 0)
                    adapter.getList().clear();
                adapter.notifyDataSetChanged();
                isFrist = true;
                page = 1;
                httpGetuser_reply_esther_comments_list();
                break;
        }
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            int position = (Integer) obj[0];
            switch (which) {
                case R.id.forum_ll1:
                    Intent intent = new Intent(MyForumActivity.this, ForumDetailActivity.class);
                    if (forum_type.equals("1")) {
                        if (adapter.getList().get(position).getStatus().equals("2")) {//已通过的帖子
                            intent.putExtra("id", adapter.getList().get(position).getId());
                            startActivity(intent);
                        } else if (adapter.getList().get(position).getStatus().equals("3")) {//未通过的帖子
                            intent = new Intent(MyForumActivity.this, EditInvitationActivity.class);
                            intent.putExtra("id", adapter.getList().get(position).getId());
                            startActivity(intent);
                        }
                    } else if (forum_type.equals("2")) {
                        intent.putExtra("id", adapter.getList().get(position).getEsther_id());
                        startActivity(intent);
                    } else if (forum_type.equals("3")) {
                        intent.putExtra("id", adapter.getList().get(position).getEsther_id());
                        startActivity(intent);
                    }
                    break;
                case R.id.tv_look_reason:
                    String reason = adapter.getList().get(position).getReturn_content();
                    View view = LayoutInflater.from(MyForumActivity.this).inflate(R.layout.item_reason, null);
                    TextView textView = (TextView) view.findViewById(R.id.tv_reason);
                    textView.setText(reason);
                    ReasonPopu popu = new ReasonPopu(MyForumActivity.this, view);
                    popu.showAtLocation(mScrollView, Gravity.CENTER, 0, 0);
                    break;

            }
            super.deal(which, obj);
        }
    };

    /**
     * 我的发帖列表
     */
    private void httpGetuser_esther_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("title", search_et.getText().toString()));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("title", search_et.getText().toString());
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getuser_esther_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                List<PostModel> new_list = new ArrayList<PostModel>();
                try {
                    JSONObject json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<PostModel>();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<PostModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<PostModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<PostModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * 我的帖子评论列表
     */
    private void httpGetuser_esther_comments_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getuser_esther_comments_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                List<PostModel> new_list = new ArrayList<PostModel>();
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<PostModel>();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<PostModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<PostModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<PostModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * 我的帖子回复列表
     */
    private void httpGetuser_reply_esther_comments_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getuser_reply_esther_comments_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                List<PostModel> new_list = new ArrayList<PostModel>();
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<PostModel>();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<PostModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<PostModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<PostModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<PostModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        if (forum_type.equals("1")) {
            httpGetuser_esther_list();
        } else if (forum_type.equals("2")) {
            httpGetuser_esther_comments_list();
        } else if (forum_type.equals("3")) {
            httpGetuser_reply_esther_comments_list();
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        if (forum_type.equals("1")) {
            httpGetuser_esther_list();
        } else if (forum_type.equals("2")) {
            httpGetuser_esther_comments_list();
        } else if (forum_type.equals("3")) {
            httpGetuser_reply_esther_comments_list();
        }
    }
}
